package es.deusto.ingenieria.aike.puzzle;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.List;

import es.deusto.ingenieria.aike.formulation.Operator;
import es.deusto.ingenieria.aike.formulation.Problem;
import es.deusto.ingenieria.aike.formulation.State;
import es.deusto.ingenieria.aike.puzzle.CarMovement.Destination;
import es.deusto.ingenieria.ingenieria.search.Node;
import es.deusto.ingenieria.ingenieria.search.SearchMethod;

public class LotProblem extends Problem {
	
	public LotProblem(State state){
		super();
		this.addInitialState(state);
	}
	
	@Override
	public boolean isFinalState(State state) {
		boolean result = false;
		if (state != null && state.getInformation() != null && state.getInformation() instanceof Environment) {
			Environment env = (Environment)state.getInformation();
			
			if (env.getCar().getY() == env.getFlag().getPosition()[0] && 
					env.getCar().getX() == env.getFlag().getPosition()[1])
			{
				result = true;
			}
		}
		return result;
	}

	public void createOperators() {
		Operator operator = new CarMovement(Destination.STRAIGHT);
		this.addOperator(operator);		
		operator = new CarMovement(Destination.LEFT);
		this.addOperator(operator);
		operator = new CarMovement(Destination.RIGHT);
		this.addOperator(operator);
	}
	
	public void solve(SearchMethod searchMethod) {
		SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss");
		System.out.println("\n* Begin '" + searchMethod.getClass().getCanonicalName() + "' (" + formatter.format(GregorianCalendar.getInstance().getTime()) + ")");
		Node finalNode = searchMethod.search(this, this.getInitialStates().get(0));
		System.out.println("* End '" + searchMethod.getClass().getCanonicalName() + "' (" + formatter.format(GregorianCalendar.getInstance().getTime()) + ")");
		
		if (finalNode != null) {
			System.out.println("* Solution found!!");
			List<String> operators = new ArrayList<String>();
			searchMethod.solutionPath(finalNode, operators);
			searchMethod.createSolutionLog(operators);
			System.out.println("PATH COST: "+operators.size());
		} else {
			System.out.println("* Solution not found :-(");
		}
	}
}